package com.fafi.selfmvc.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.async.WebAsyncTask;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.io.IOException;
import java.util.concurrent.Callable;

@Controller
public class AsyncTaskController {
	private static final Log logger = LogFactory.getLog(AsyncTaskController.class);

	@RequestMapping(value="/longtimetask", method = RequestMethod.GET)
	public WebAsyncTask<ModelAndView>/*Callable<ModelAndView>*/ longTimeTask(){
		logger.info("/longtimetask被调用 thread id is : " + Thread.currentThread().getId());
		Callable<ModelAndView> callable = new Callable<ModelAndView>() {

			@Override
			public ModelAndView call() throws Exception {
				Thread.sleep(8000); //假设是一些长时间任务
				ModelAndView mav = new ModelAndView("asynctask");
				mav.addObject("result", "执行成功");
				logger.info("执行成功 thread id is : " + Thread.currentThread().getId());
				return mav;
			}
		};
		return new WebAsyncTask<ModelAndView>(callable);
		//return callable;
	}

	@RequestMapping("/events")
	public ResponseBodyEmitter handleEmitter() {
		ResponseBodyEmitter emitter = new ResponseBodyEmitter();

		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					emitter.send("step1");
					Thread.sleep(1000);
					emitter.send("step2");
					Thread.sleep(1000);
					emitter.send("complete");
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}).start();
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					emitter.send("step4");
					Thread.sleep(2000);
					emitter.send("step5");
					Thread.sleep(2000);
					emitter.send("step6");
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}).start();
		return emitter;
	}
}
